/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.authorize.domain.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.IteratorUtils;
import org.cshoo.tattoo.authorize.domain.po.Microservice;
import org.cshoo.tattoo.authorize.domain.repository.IMicroserviceRepository;
import org.cshoo.tattoo.embed.infra.utils.AuditFieldsUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author 杨翼
 * @since 1.0
 */
@Service
@Slf4j
public class MicroserviceService {

    @Resource
    private IMicroserviceRepository microserviceRepository;

    /**
     * 添加一个微服务
     * @param microservice 微服务
     */
    public void addMicroservice(Microservice microservice) {
        AuditFieldsUtils.setAddAuditFields(microservice);
        microserviceRepository.save(microservice);
    }

    /**
     * 修改一个微服务
     * @param microservice 微服务
     */
    public void updateMicroservice(Microservice microservice) {
        AuditFieldsUtils.setUpdateAuditFields(microservice);
        microserviceRepository.save(microservice);
    }

    /**
     * 删除一个微服务
     * @param id id
     */
    public void deleteMicroservice(Long id) {
        microserviceRepository.deleteById(id);
    }

    /**
     * 查询所有微服务
     * @return 微服务
     */
    @SuppressWarnings("unchecked")
    public List<Microservice> findAllMicroservice() {
        Iterable<Microservice> microservices = microserviceRepository.findAll();
        return IteratorUtils.toList(microservices.iterator());
    }

    /**
     * 查找一个微服务
     * @param microserviceId 微服务id
     * @return 微服务
     */
    public Microservice findMicroservice(Long microserviceId) {
        log.info("microserviceId:{}",microserviceId);
        Optional<Microservice> microserviceOptional = microserviceRepository.findById(microserviceId);
        return microserviceOptional.orElse(null);
    }
}
